<template>
    <view>
        <block v-if="common_site_type == 1">
            <component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
        </block>
        <block v-else>
            <view v-if="goods_list.length > 0" class="page_big">
                <!-- 销售+自提 模式选择 -->
                <view v-if="common_site_type == 4" class="buy-header-nav oh tc">
                    <block v-for="(item, index) in buy_header_nav" :key="index">
                        <view :class="'item fl ' + (site_model == item.value ? 'cr-main' : 'cr-666')" :data-value="item.value" @tap="buy_header_nav_event">{{ item.name }}</view>
                    </block>
                </view>

                <!-- 地址 -->
                <block v-if="common_site_type == 0 || common_site_type == 2 || common_site_type == 4">
                    <view class="address bg-white arrow-right" @tap="address_event">
                        <view v-if="address != null">
                            <view class="address-base oh">
                                <text v-if="(address.alias || null) != null" class="address-alias">{{ address.alias }}</text>
                                <text>{{ address.name }}</text>
                                <text class="fr">{{ address.tel }}</text>
                            </view>
                            <view class="address-detail oh">
								<image class="icon fl" :src="groups_static_url+'mini/user-address.png'" mode="widthFix" />
                                <view class="text fr">{{ address.province_name }}{{ address.city_name }}{{ address.county_name }}{{ address.address }}</view>
                            </view>
                        </view>
                        <view v-if="address == null" class="no-address cr-888">
                            {{ common_site_type == 0 || (common_site_type == 4 && site_model == 0) ? lang_info.buy_address_type_1_tips : lang_info.buy_address_type_2_tips}}
                        </view>
                    </view>
                    <view class="address-divider spacing-mb"></view>
                </block>

                <!-- 商品 -->
                <view class="goods bg-white spacing-mb">
                    <view class="goods-item oh" v-for="(item, index) in goods_list" :key="index">
                        <image class="goods-image fl" :src="item.images" mode="aspectFill" />

                        <view class="goods-base">
                            <view class="goods-title multi-text">{{ item.title }}</view>
                            <block v-if="item.spec != null">
                                <view class="goods-spec cr-888" v-for="(spec, index1) in item.spec" :key="index1">{{ spec.type }}:{{ spec.value }}</view>
                            </block>
                        </view>

                        <view class="oh goods-price">
                            <text class="sales-price">{{ currency_symbol }}{{ item.price }}</text>
                            <text v-if="item.original_price > 0" class="original-price">{{ currency_symbol }}{{ item.original_price }}</text>
                            <text class="buy-number cr-888">x{{ item.stock }}</text>
                        </view>
                    </view>
                </view>

                <!-- 留言 -->
                <view class="content-textarea-view bg-white spacing-mb padding-main">
                    <textarea v-if="!popup_plugins_coupon_status" @input="bind_user_note_event" :value="user_note_value" maxlength="60" :placeholder="lang_info.buy_leave_message_placeholder" class="wh-auto" />
                    <view v-if="popup_plugins_coupon_status" class="cr-888">{{ user_note_value || lang_info.buy_leave_message_placeholder }}</view>
                </view>

				<!-- 优惠劵 -->

                <!-- 扩展数据展示 -->
                <view v-if="extension_data.length > 0" class="extension-list spacing-mb">
                    <view class="item oh" v-for="(item, index) in extension_data" :key="index">
                        <text class="cr-666 fl">{{ item.name }}</text>

                        <text class="text-tips fr">{{ item.tips }}</text>
                    </view>
                </view>

                <!-- 支付方式 -->
                <view v-if="payment_list.length > 0 && common_order_is_booking != 1" class="payment-list payment-list2 bg-white oh">
                    <view class="item tc fl" v-for="(item, index) in payment_list" :key="index">
                        <view :class="'item-content br ' + (item.selected || '')" :data-value="item.id" @tap="payment_event">
                            <image v-if="(item.logo || null) != null" class="icon" :src="item.logo" mode="widthFix" />
                            <text>{{ item.name }}</text>
                        </view>
                    </view>
                </view>
                <view class="bg-white oh">
                    <view class="paynotice">
                        {{lang_info.buy_paynotice_tips_before}}
                        <text>30 {{lang_info.buy_paynotice_tips_minute}}</text>
                        {{lang_info.buy_paynotice_tips_after}}
                        <!--（使用的优惠券则不会退还）-->
                    </view>
                </view>
                <!-- 导航 -->
                <view class="buy-nav oh wh-auto bg-white bottom-line-exclude">
                    <view class="nav-base bg-white fl single-text">
                        <text>{{lang_info.buy_price_all_text}}</text>
                        <text class="sales-price">{{ currency_symbol }}{{ total_price }}</text>
                    </view>
                    <view class="fr nav-submit">
                        <button class="bg-main wh-auto" type="default" @tap="buy_submit_event" :disabled="buy_submit_disabled_status" hover-class="none">{{lang_info.buy_price_btn_text}}</button>
                    </view>
                </view>
            </view>

            <view v-if="goods_list.length == 0">
                <component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
            </view>
			<!-- 支付弹窗 -->
			<component-payment :diyTheme="diytheme" 
			    :propCurrencySymbol="currency_symbol"
			    :propPayUrl="pay_url"
			    :propQrcodeUrl="qrcode_url"
			    propPayDataKey="id"
			    :propPaymentList="payment_list"
			    :propTempPayValue="temp_pay_value"
			    :propPayPrice="pay_price"
			    :propPaymentId="payment_id"
			    :propIsRedirectTo="true"
			    :propToFailPage="to_fail_page"
			    :propToAppointPage="to_appoint_page"
			    :propIsShowPayment="is_show_payment_popup"
			    @close-payment-popup="payment_popup_event_close"
			></component-payment>
        </block>
    </view>
</template>

<script>
const app = getApp();
import componentPopup from '@/components/popup/popup';
import componentQuickNav from "@/components/quick-nav/quick-nav";
import componentBadge from '@/components/badge/badge';
import componentNoData from "@/components/no-data/no-data";
import componentBottomLine from "@/components/bottom-line/bottom-line";
import componentOnlineService from "@/components/online-service/online-service";
import componentPayment from '@/components/payment/payment';
import { groups_base_info, clear_user_cach } from '@/pages/fcc/groups/public/common.js';
var groups_static_url = app.globalData.get_static_url('groups', true);
var common_static_url = app.globalData.get_static_url('common');
export default {
    components: {
        componentQuickNav,
        componentPopup,
        componentBadge,
        componentNoData,
        componentBottomLine,
        componentOnlineService,
		componentPayment
    },
    data() {
        return {
            currency_symbol: app.globalData.currency_symbol(),
            data_list_loding_status: 1,
			groups_static_url: groups_static_url,
			common_static_url: common_static_url,
            buy_submit_disabled_status: false,
            data_list_loding_msg: '',
            params: null,
            goods_list: [],
            address: null,
            address_id: null,
            total_price: 0,
            user_note_value: '',
            is_first: 1,
            extension_data: [],
            common_order_is_booking: 0,
            common_site_type: 0,
            extraction_address: [],
            site_model: 0,
            buy_header_nav: [
                { name: '快递邮寄', value: 0 },
                { name: '自提点取货', value: 2 },
            ],

            // 优惠劵
            plugins_coupon_data: null,
            plugins_use_coupon_id: 0,
            plugins_choice_coupon_value: {},
            popup_plugins_coupon_status: false,
			
			// 支付弹窗参数
			pay_url: '',
			qrcode_url: '',
			payment_list: [],
			temp_pay_value: '',
			is_show_payment_popup: false,
			pay_price: 0,
			payment_id: 0,
			// 支付失败跳转的页面
			to_fail_page: '/pages/fcc/groups/order/order',
			to_appoint_page: '/pages/fcc/groups/order/order',
			
            diytheme:{
            	'main_color':'#fd302d',
            	'second_color':'#f29701',
            	'ligth_color_1':'#feeaeb',
            	'ligth_color_2':'#feeaeb',
            	'ligth_color_deg':0,
            	'price_color':'#fd302d',
            },

            length: 0,
			// 多语言
			lang_info:{},
			data_bottom_line_msg:''
        };
    },
	onLoad(params) {
	    //params['data'] = '{"buy_type":"goods","goods_id":"1","stock":"1","spec":"[]"}';
	    if ((params.data || null) != null && app.globalData.get_length(JSON.parse(decodeURIComponent(params.data))) > 0) {
	        this.setData({
	            params: JSON.parse(decodeURIComponent(params.data))
	        });
	
	        // 删除地址缓存
	        uni.removeStorageSync(app.globalData.data.cache_buy_user_address_select_key);
	    }
	},
    onShow() {
        this.init();
    },
    // 下拉刷新
    onPullDownRefresh() {
        this.init();
    },
    methods: {
		// 设置本页参数
		init_before(data){
			var self = this;
			return new Promise((resolve, reject) => {
				var temp_buy_header_nav = self.buy_header_nav;
				temp_buy_header_nav[0].name = data.buy_address_type_1_text;
				temp_buy_header_nav[1].name = data.buy_address_type_2_text;
				self.setData({
					lang_info:data,
					currency_symbol: app.globalData.get_config('currency_symbol'),
					common_app_is_online_service: app.globalData.get_config('config.common_app_is_online_service'),
					data_bottom_line_msg: data.data_bottom_line_msg || '到底啦~',
					buy_header_nav: temp_buy_header_nav,
					pay_url: app.globalData.get_request_url('pay', 'index', 'groups'),
					qrcode_url: app.globalData.get_request_url('paycheck', 'index', 'groups'),
				});
				uni.setNavigationBarTitle({
				    title: data.buy_order_page_title
				});
				resolve();
			});
		},
		init() {
			groups_base_info()
			.then(data=>{
				this.init_before(data)
				.then(()=>{
					this.init_real();
				});
			});
		},
		
		init_real(){
            // 订单参数信息是否正确
            if (this.params == null) {
                this.setData({
                    data_list_loding_status: 2,
                    data_list_loding_msg: this.lang_info.buy_order_error_msg
                });
                uni.stopPullDownRefresh();
                return false;
            } 
			
			// 本地缓存地址
            if (this.is_first == 0) {
				var cache_address = uni.getStorageSync(app.globalData.data.cache_buy_user_address_select_key);
				if ((cache_address || null) != null) {
				    this.setData({
				        address: cache_address,
				        address_id: cache_address.id
				    });
				}
            } 
			
			// 加载loding
            uni.showLoading({
                title: this.lang_info.loading_tips
            });
            this.setData({
                data_list_loding_status: 1
            });
            var data = this.params;
            data['address_id'] = this.address_id;
            data['payment_id'] = this.payment_id;
            data['coupon_id'] = this.plugins_use_coupon_id;
            data['site_model'] = this.site_model;
            uni.request({
                url: app.globalData.get_request_url('buy', 'index', 'groups'),
                method: 'POST',
                data: data,
                dataType: 'json',
                success: (res) => {
                    uni.stopPullDownRefresh();
                    uni.hideLoading();
                    console.log(res);

                    if (res.data.code == 0) {
                        var data = res.data.data;

                        if (data.goods_list.length == 0) {
                            this.setData({
                                data_list_loding_status: 0
                            });
                        } else {
                            this.setData({
                                goods_list: data.goods_list,
                                total_price: data.base.actual_price,
                                extension_data: data.extension_data || [],
                                data_list_loding_status: 3,
                                common_order_is_booking: data.common_order_is_booking || 0,
                                common_site_type: data.common_site_type || 0,
                                extraction_address: data.base.extraction_address || [],
                                plugins_coupon_data: data.plugins_coupon_data || null,
								payment_id: data.payment_id || 0 //add by YX
                            }); 
							
							// 优惠劵选择处理
                            if ((data.plugins_coupon_data || null) != null) {
                                if ((data.plugins_coupon_data.coupon_choice || null) != null) {
                                    this.setData({
                                        plugins_choice_coupon_value: data.plugins_coupon_data.coupon_choice.coupon.desc
                                    });
                                } else {
                                    var coupon_count = (data.plugins_coupon_data.coupon_list || null) != null ? data.plugins_coupon_data.coupon_list.length : 0;
                                    this.setData({
                                        plugins_choice_coupon_value: coupon_count > 0 ? this.lang_info.buy_order_coupon_can_use_before + coupon_count + this.lang_info.buy_order_coupon_can_use_after : this.lang_info.buy_order_coupon_can_use_zero
                                    });
                                }
                            } 
							
							// 地址
                            this.setData({
                                address: data.base.address || null,
                                address_id: (data.base.address || null) != null ? data.base.address.id : null
                            });
                            uni.setStorage({
                                key: app.globalData.data.cache_buy_user_address_select_key,
                                data: data.base.address || null
                            }); 
							
							// 支付方式
                            this.payment_list_data(data.payment_list);
                        }
                    } else {
                        this.setData({
                            data_list_loding_status: 2,
                            data_list_loding_msg: res.data.msg
                        });

                        if (app.globalData.is_login_check(res.data, this, 'init')) {
                            app.globalData.showToast(res.data.msg);
                        }
                    }
                },
                fail: () => {
                    uni.stopPullDownRefresh();
                    uni.hideLoading();
                    this.setData({
                        data_list_loding_status: 2,
                        data_list_loding_msg: this.lang_info.request_data_error_tips
                    });
                    app.globalData.showToast(this.lang_info.request_data_error_tips);
                },
				complete:()=>{
					this.setData({
					    is_first: 0
					});
				}
            });
        },

        // 用户留言事件
        bind_user_note_event(e) {
            this.setData({
                user_note_value: e.detail.value
            });
        },

        // 提交订单
        buy_submit_event(e) {
            // 表单数据
            var data = this.params;
            data['address_id'] = this.address_id;
            data['payment_id'] = this.payment_id;
            data['user_note'] = this.user_note_value;
            data['coupon_id'] = this.plugins_use_coupon_id;
            data['site_model'] = this.site_model; // 数据验证

            var validation = [];

            if (this.common_site_type == 0 || this.common_site_type == 2 || this.common_site_type == 4) {
                validation.push({
                    fields: 'address_id',
                    msg: this.lang_info.buy_order_submit_check_address_tips,
                    is_can_zero: 1
                });
            }

            if (this.common_order_is_booking != 1) {
                validation.push({
                    fields: 'payment_id',
                    msg: this.lang_info.buy_order_submit_check_payment_tips,
                });
            }

            if (app.globalData.fields_check(data, validation)) {
                // 加载loding
                uni.showLoading({
                    title:this.lang_info.loading_tips
                });
                this.setData({
                    buy_submit_disabled_status: true
                });
                uni.request({
                    url: app.globalData.get_request_url('buyadd', 'index', 'groups'),
                    method: 'POST',
                    data: data,
                    dataType: 'json',
                    success: (res) => {
                        uni.hideLoading();
                        console.log(res);

                        if (res.data.code == 0) {
                            if (res.data.data.order.status == 1) {
								uni.setStorageSync(app.globalData.data.cache_page_pay_key, { type: 1 });
								this.setData({
								    is_show_payment_popup: true,
								    pay_price: res.data.data.order.total_price,
								    temp_pay_value: res.data.data.order.id
								});
                                /*uni.redirectTo({
                                    url: '/pages/fcc/groups/order/order?is_pay=1&order_id=' + res.data.data.order.id
                                });*/
                            } else {
                                app.globalData.url_open('/pages/fcc/groups/order/order', true);
                            }
                        } else {
                            app.globalData.showToast(res.data.msg);
                            this.setData({
                                buy_submit_disabled_status: false
                            });
                        }
                    },
                    fail: () => {
                        uni.hideLoading();
                        this.setData({
                            buy_submit_disabled_status: false
                        });
                        app.globalData.showToast(this.lang_info.request_data_error_tips);
                    }
                });
            }
        },

        // 支付方式选择
        payment_event(e) {
            this.setData({
                payment_id: e.currentTarget.dataset.value
            });
            this.payment_list_data(this.payment_list);
            this.init();
        },

        // 支付方式数据处理
        payment_list_data(data) {
            if (this.payment_id != 0) {
                for (var i in data) {
                    if (data[i]['id'] == this.payment_id) {
                        data[i]['selected'] = 'selected';
                    } else {
                        data[i]['selected'] = '';
                    }
                }
            }

            this.setData({
                payment_list: data || []
            });
        },

        // 优惠劵弹层开启
        plugins_coupon_open_event(e) {
            this.setData({
                popup_plugins_coupon_status: true
            });
        },

        // 优惠劵弹层关闭
        plugins_coupon_close_event(e) {
            this.setData({
                popup_plugins_coupon_status: false
            });
        },

        // 优惠劵选择
        plugins_coupon_use_event(e) {
            var index = e.currentTarget.dataset.index;
            var value = e.currentTarget.dataset.value;
            this.setData({
                plugins_use_coupon_id: value,
                popup_plugins_coupon_status: false
            });
            this.init();
        },

        // 不使用优惠劵
        plugins_coupon_not_use_event(e) {
            this.setData({
                plugins_use_coupon_id: 0,
                popup_plugins_coupon_status: false
            });
            this.init();
        },

        // 地址选择事件
        address_event(e) {
            if (this.common_site_type == 0 || (this.common_site_type == 4 && this.site_model == 0)) {
                app.globalData.url_open('/pages/user-address/user-address?is_back=1');
            } else {
                if (this.common_site_type == 2 || (this.common_site_type == 4 && this.site_model == 2)) {
                    app.globalData.url_open('/pages/extraction-address/extraction-address?is_back=1&is_buy=1');
                } else {
                    app.globalData.showToast(this.lang_info.buy_order_can_not_use_address_tips);
                }
            }
        },
		
		payment_popup_event_close() {
		    this.setData({
		        is_show_payment_popup: false,
				buy_submit_disabled_status: false
		    });
		},

        // 销售+自提 模式选择事件
        buy_header_nav_event(e) {
            var value = e.currentTarget.dataset.value || 0;

            if (value != this.site_model) {
                // 数据设置
                this.setData({
                    address: null,
                    address_id: null,
                    site_model: value
                }); // 删除地址缓存

                uni.removeStorageSync(app.globalData.data.cache_buy_user_address_select_key); // 数据初始化

                this.init();
            }
        }
    }
};
</script>
<style>
@import './buy.css';
</style>
